﻿using ERP.WorkforceManage;
using ERP.WorkforceManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Linq;
using Microsoft.AspNetCore.Authorization;

namespace ERP.Web.Controllers
{
    [AllowAnonymous]
    public class ClassesController : Controller
    {
        private readonly IClassesService _classesService;

        public ClassesController(IClassesService classesService)
        {
            _classesService = classesService;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取班次列表（分页）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetList([FromBody] PagedClassesRequestDto input)
        {
            try
            {
                var result = await _classesService.GetPagedListAsync(input);
                return Ok(new { code = 0, msg = "", count = result.TotalCount, data = result.Items });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 1, msg = ex.Message });
            }
        }

        /// <summary>
        /// 获取班次详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(int id)
        {
            try
            {
                var result = await _classesService.GetAsync(id);
                return Ok(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> CreateClasses([FromBody] CreateClassesDto input)
        {
            try
            {
                if (input == null)
                {
                    return BadRequest(new { success = false, msg = "输入数据为空" });
                }

                // 打印接收到的数据
                Console.WriteLine($"接收到的班次数据: SerialNumber={input.SerialNumber}, ClassesName={input.ClassesName}, StartTime={input.StartTime}, EndTime={input.EndTime}");

                // 数据验证
                if (string.IsNullOrWhiteSpace(input.ClassesName))
                {
                    return BadRequest(new { success = false, msg = "班次名称不能为空" });
                }

                if (string.IsNullOrWhiteSpace(input.StartTime))
                {
                    return BadRequest(new { success = false, msg = "开始时间不能为空" });
                }

                if (string.IsNullOrWhiteSpace(input.EndTime))
                {
                    return BadRequest(new { success = false, msg = "结束时间不能为空" });
                }

                var result = await _classesService.CreateAsync(input);
                return Ok(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"创建班次时发生错误: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                    Console.WriteLine($"内部异常堆栈: {ex.InnerException.StackTrace}");
                }
                
                return StatusCode(500, new { 
                    success = false, 
                    msg = "服务器内部错误，请联系管理员"
                });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Update(int id, [FromBody] UpdateClassesDto input)
        {
            try
            {
                var result = await _classesService.UpdateAsync(id, input);
                return Ok(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _classesService.DeleteAsync(id);
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> BatchDelete([FromBody] int[] ids)
        {
            try
            {
                // 将int[]转换为List<int>
                var idList = ids.ToList();
                
                await _classesService.BatchDeleteAsync(idList);
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, msg = ex.Message });
            }
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateClassesDto input)
        {
            // 直接调用CreateClasses方法
            return await CreateClasses(input);
        }
    }
}
